<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 物料管理
 *
 * @icon fa fa-cubes
 * @remark 管理生产所需的物料信息
 */
class Material extends Backend
{
    /**
     * Material模型对象
     * @var \app\admin\model\scanwork\Material
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Material;
        $this->view->assign("statusList", $this->model->getStatusList());
        // 从数据库获取分类列表
        $categoryList = \app\admin\model\scanwork\MaterialCategory::where('status', 1)->column('name', 'id');
        $this->view->assign("categoryList", $categoryList);
        $this->view->assign("unitList", $this->model->getUnitList());
    }

    /**
     * 合并同名物料
     */
    public function mergeDuplicates()
    {
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                // 查找所有同名物料
                $duplicates = Db::name('scanwork_material')
                    ->field('name, GROUP_CONCAT(id) as ids, GROUP_CONCAT(stock) as stocks')
                    ->group('name')
                    ->having('COUNT(*) > 1')
                    ->select();

                $mergedCount = 0;
                foreach ($duplicates as $duplicate) {
                    $ids = explode(',', $duplicate['ids']);
                    $stocks = explode(',', $duplicate['stocks']);
                    
                    if (count($ids) > 1) {
                        // 保留第一个物料，合并其他物料的库存
                        $keepId = $ids[0];
                        $totalStock = array_sum($stocks);
                        
                        // 更新保留物料的库存
                        Db::name('scanwork_material')
                            ->where('id', $keepId)
                            ->update(['stock' => $totalStock]);
                        
                        // 更新所有相关表的物料ID
                        $deleteIds = array_slice($ids, 1);
                        
                        // 更新工序物料配置
                        Db::name('scanwork_process_material')
                            ->where('material_id', 'in', $deleteIds)
                            ->update(['material_id' => $keepId]);
                        
                        // 更新订单物料
                        Db::name('scanwork_order_material')
                            ->where('material_id', 'in', $deleteIds)
                            ->update(['material_id' => $keepId]);
                        
                        // 更新采购申请
                        Db::name('scanwork_purchase_request')
                            ->where('material_id', 'in', $deleteIds)
                            ->update(['material_id' => $keepId]);
                        
                        // 更新入库单明细
                        Db::name('scanwork_purchase_inbound_item')
                            ->where('material_id', 'in', $deleteIds)
                            ->update(['material_id' => $keepId]);
                        
                        // 更新库存记录
                        Db::name('scanwork_inventory_record')
                            ->where('material_id', 'in', $deleteIds)
                            ->update(['material_id' => $keepId]);
                        
                        // 删除重复的物料记录
                        Db::name('scanwork_material')
                            ->where('id', 'in', $deleteIds)
                            ->delete();
                        
                        $mergedCount++;
                    }
                }
                
                Db::commit();
                $this->success("成功合并 {$mergedCount} 组同名物料");
            } catch (Exception $e) {
                Db::rollback();
                $this->error('合并失败：' . $e->getMessage());
            }
        }
        
        // 显示合并预览
        $duplicates = Db::name('scanwork_material')
            ->field('name, GROUP_CONCAT(id) as ids, GROUP_CONCAT(stock) as stocks, COUNT(*) as count')
            ->group('name')
            ->having('COUNT(*) > 1')
            ->select();
        
        $this->view->assign('duplicates', $duplicates);
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['defaultSupplier', 'category'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // 添加库存状态标记
            foreach ($list as $item) {
                // 确保stock_status_text属性被正确计算
                $item->append(['stock_status_text']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取供应商列表
        $supplierList = \app\admin\model\scanwork\Supplier::where('status', 1)->select();
        $this->view->assign('supplierList', $supplierList);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $suppliers = $this->request->post("suppliers/a"); // 供应商报价数据
            
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 检查物料名称是否重复
                $existingMaterial = $this->model->where('name', $params['name'])->find();
                if ($existingMaterial) {
                    $this->error("物料名称 '{$params['name']}' 已存在，请使用不同的名称或使用合并功能处理重复物料");
                }
                
                // 自动生成物料编码
                if (empty($params['code'])) {
                    $params['code'] = $this->generateMaterialCode($params['category']);
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 保存供应商报价
                    if ($result !== false && !empty($suppliers)) {
                        $materialId = $this->model->id;
                        
                        foreach ($suppliers as $supplierData) {
                            if (!empty($supplierData['supplier_id']) && !empty($supplierData['price'])) {
                                \app\admin\model\scanwork\MaterialSupplier::create([
                                    'material_id' => $materialId,
                                    'supplier_id' => $supplierData['supplier_id'],
                                    'price' => $supplierData['price'],
                                    'min_order_qty' => isset($supplierData['min_order_qty']) ? $supplierData['min_order_qty'] : 1,
                                    'delivery_days' => isset($supplierData['delivery_days']) ? $supplierData['delivery_days'] : 7,
                                    'is_preferred' => isset($supplierData['is_preferred']) ? $supplierData['is_preferred'] : 0,
                                    'quality_rating' => isset($supplierData['quality_rating']) ? $supplierData['quality_rating'] : 5,
                                    'service_rating' => isset($supplierData['service_rating']) ? $supplierData['service_rating'] : 5,
                                    'status' => 1
                                ]);
                            }
                        }
                        
                        // 更新物料当前价格
                        $material = $this->model->get($materialId);
                        $material->updateCurrentPrice();
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取供应商列表
        $supplierList = \app\admin\model\scanwork\Supplier::where('status', 1)->select();
        $this->view->assign('supplierList', $supplierList);
        
        // 获取物料的供应商报价列表
        $materialSuppliers = \app\admin\model\scanwork\MaterialSupplier::with(['supplier'])
            ->where('material_id', $ids)
            ->select();
        $this->view->assign('materialSuppliers', $materialSuppliers);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $suppliers = $this->request->post("suppliers/a"); // 供应商报价数据
            
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 检查物料名称是否重复（排除当前物料）
                $existingMaterial = $this->model->where('name', $params['name'])->where('id', '<>', $ids)->find();
                if ($existingMaterial) {
                    $this->error("物料名称 '{$params['name']}' 已存在，请使用不同的名称或使用合并功能处理重复物料");
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    
                    // 更新供应商报价
                    if ($result !== false && !empty($suppliers)) {
                        // 先删除原有报价
                        \app\admin\model\scanwork\MaterialSupplier::where('material_id', $ids)->delete();
                        
                        // 重新创建报价
                        foreach ($suppliers as $supplierData) {
                            if (!empty($supplierData['supplier_id']) && !empty($supplierData['price'])) {
                                \app\admin\model\scanwork\MaterialSupplier::create([
                                    'material_id' => $ids,
                                    'supplier_id' => $supplierData['supplier_id'],
                                    'price' => $supplierData['price'],
                                    'min_order_qty' => isset($supplierData['min_order_qty']) ? $supplierData['min_order_qty'] : 1,
                                    'delivery_days' => isset($supplierData['delivery_days']) ? $supplierData['delivery_days'] : 7,
                                    'is_preferred' => isset($supplierData['is_preferred']) ? $supplierData['is_preferred'] : 0,
                                    'quality_rating' => isset($supplierData['quality_rating']) ? $supplierData['quality_rating'] : 5,
                                    'service_rating' => isset($supplierData['service_rating']) ? $supplierData['service_rating'] : 5,
                                    'status' => 1
                                ]);
                            }
                        }
                        
                        // 更新物料当前价格
                        $row->updateCurrentPrice();
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的工序物料配置
                    $processCount = \app\admin\model\scanwork\ProcessMaterial::where('material_id', $item->id)->count();
                    if ($processCount > 0) {
                        throw new Exception("物料【{$item->name}】还在{$processCount}个工序中使用，无法删除");
                    }
                    
                    // 检查是否有关联的订单需求
                    $orderCount = \app\admin\model\scanwork\OrderMaterial::where('material_id', $item->id)->count();
                    if ($orderCount > 0) {
                        throw new Exception("物料【{$item->name}】还在{$orderCount}个订单中使用，无法删除");
                    }
                    
                    // 删除物料的供应商报价
                    \app\admin\model\scanwork\MaterialSupplier::where('material_id', $item->id)->delete();
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看物料详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取供应商报价列表
        $suppliers = \app\admin\model\scanwork\MaterialSupplier::with(['supplier'])
            ->where('material_id', $ids)
            ->order('price', 'asc')
            ->select();
        
        // 获取使用该物料的工序
        $processes = \app\admin\model\scanwork\ProcessMaterial::with(['model.product', 'process'])
            ->where('material_id', $ids)
            ->select();
        
        // 获取最近采购记录
        $purchases = \app\admin\model\scanwork\PurchaseRecord::with(['supplier', 'order'])
            ->where('material_id', $ids)
            ->order('createtime', 'desc')
            ->limit(10)
            ->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('suppliers', $suppliers);
        $this->view->assign('processes', $processes);
        $this->view->assign('purchases', $purchases);
        
        return $this->view->fetch();
    }

    /**
     * 库存预警列表
     */
    public function stockAlert()
    {
        $list = $this->model
            ->where('status', 1)
            ->where('stock', '<', \think\Db::raw('min_stock'))
            ->order('stock', 'asc')
            ->select();
        
        $this->view->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 生成物料编码
     */
    private function generateMaterialCode($category = '')
    {
        $prefix = 'MAT';
        
        // 根据分类生成不同前缀
        $categoryPrefix = [
            '面料' => 'FAB',
            '辅料' => 'ACC',
            '五金件' => 'HAR',
            '填充物' => 'FIL',
            '包装材料' => 'PKG'
        ];
        
        if (isset($categoryPrefix[$category])) {
            $prefix = $categoryPrefix[$category];
        }
        
        $count = $this->model->where('category', $category)->count();
        $code = $prefix . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        
        // 检查是否重复
        while ($this->model->where('code', $code)->count() > 0) {
            $count++;
            $code = $prefix . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        }
        
        return $code;
    }
}

